import { ObjectLiteral, SelectQueryBuilder, ValueTransformer } from 'typeorm'
import axios from 'axios'
import * as dayjs from 'dayjs'
/**
 * 公共时间范围查询工具函数
 * @param qb 查询构建器
 * @param field 要查询的数据库字段名（如 'create_time'）
 * @param startParam query对象中开始时间的参数名（如 'start'）
 * @param endParam query对象中结束时间的参数名（如 'end'）
 * @param query 请求参数对象
 */
export function handleTimeRange<T extends ObjectLiteral>(
  qb: SelectQueryBuilder<T>,
  tableName: string,
  field: string,
  startParam: string,
  endParam: string,
  query: Record<string, any>
): void {
  const start = query[startParam]
  const end = query[endParam]

  if (start || end) {
    const startVal = start ? Math.floor(Number(start)) : undefined
    const endVal = end ? Math.floor(Number(end)) : undefined

    if (startVal && endVal) {
      qb.andWhere(`${tableName}.${field} BETWEEN :${field}_start AND :${field}_end`, {
        [`${field}_start`]: startVal,
        [`${field}_end`]: endVal
      })
    } else if (startVal) {
      qb.andWhere(`${tableName}.${field} >= :${field}_start`, {
        [`${field}_start`]: startVal
      })
    } else if (endVal) {
      qb.andWhere(`${tableName}.${field} <= :${field}_end`, {
        [`${field}_end`]: endVal
      })
    }
  }
}

// 处理对象值
export function handleObjValue(data: Record<string, any>): Record<string, any> {
  return Object.fromEntries(
    Object.entries(data).filter(([_, value]) => {
      // 排除 undefined、null、空字符串
      return value !== undefined && value !== null && value !== '';
    })
  )
}

/**
 * 提取有效的更新字段
 * @param data 原始数据对象
 * @param validFields 允许更新的字段名数组
 * @returns 过滤后的纯净对象
 */
export function updateFields<T extends Record<string, any>>(
  data: T,
  validFields: Array<keyof T>
): Partial<T> {
  return Object.fromEntries(
    Object.entries(data).filter(
      ([key, value]) =>
        validFields.includes(key as keyof T) &&
        value !== undefined &&
        value !== null &&
        value !== ''
    )
  ) as Partial<T>
}

const CORP_INFO = {
  id: 'ww185731c8e7b59314',
  secret: 'IMNQWSwYs6IIdcNKz57ERLMFUKeTXUTkWoIHI8I_uMI',
  agent_id: 1000002, // 自建应用ID
}

// 自建应用推送消息
export async function sendWeComMsg(content = '', touser = '@all') {
  const curDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const tokenResp = await axios.get('https://qyapi.weixin.qq.com/cgi-bin/gettoken', {
    params: {
      corpid: CORP_INFO.id,
      corpsecret: CORP_INFO.secret
    }
  })
  const access_token = tokenResp.data.access_token

  try {
    const resp = await axios.post(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${access_token}`, {
      touser,
      msgtype: 'text',
      agentid: CORP_INFO.agent_id,
      text: {
        content: content || `${curDate}的测试消息~`
      },
      safe: 0
    })
    console.log('消息发送接口返回：', resp.data)
  } catch (err) {
    if (err.response) {
      // 请求已发出，服务器有响应，但状态码不是 2xx
      console.error('消息发送失败，响应数据：', err.response.data)
      console.error('状态码：', err.response.status)
      console.error('响应头：', err.response.headers)
    }
  }
}
// 获取当前公网IP
export async function getPublicIp() {
  try {
    const response = await axios.get('https://ifconfig.me')
    return response.data.trim()
  } catch (error) {
    console.error('获取公网 IP 失败：', error)
    throw error
  }
}

// 机器人推送消息
export async function robotMsg(content: string, atList: string[] = []) {
  return new Promise(async (resolve, reject) => {
    try {
      const params = {
        method: 'POST',
        url: `https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b53cb4e7-7961-42d3-9126-cb0910982961`,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        data: JSON.stringify({
          //携带的数据
          "msgtype": "text",
          "text": {
            content,
            mentioned_list: atList
          }
        }),
      }
      const { data } = await axios(params)
      if (data.errcode == 0) {
        resolve(data)
      } else {
        reject(data.errmsg || '发送失败')
      }

    } catch (error) {
      reject(error.message || error)
    }
  })
}

export function getCurrentTime(format = 'HH:mm') {
  return dayjs().format(format)
}

// 手机号脱敏
export function maskPhone(phone: string) {
  if (!phone) return '';
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}

// 邮箱脱敏：显示前3位和后4位，中间用***代替
export function maskEmail(email: string) {
  if (!email) return ''
  const [localPart, domain] = email.split('@')
  if (localPart.length <= 3) {
    return `${localPart}***@${domain}`
  }
  return `${localPart.slice(0, 3)}***@${domain}`
}

// 判断是否为工作日（包含调休补班）
export async function isWorkday(date: string): Promise<boolean> {
  try {
    const response = await axios.get(`https://timor.tech/api/holiday/info/${date}`)
    const { type } = response.data
    // 0：工作日，3：调休补班
    return type.type === 0 || type.type === 3
  } catch (error) {
    console.error('查询节假日失败：', error)
    // 异常时默认按原逻辑（周一到周五）执行，避免服务中断
    const weekDay = new Date(date).getDay()
    return weekDay >= 1 && weekDay <= 5
  }
}

export function formatFee(totalFee = 0, totalCost = 0, decimal = 2) {
  const fee = Number(totalFee) ?? 0
  const cost = Number(totalCost) ?? 0

  if (!fee || !cost || isNaN(fee) || isNaN(cost)) {
    return '0'
  }

  const ratio = fee - cost
  if (isNaN(ratio)) return '0'

  const isInteger = Math.abs(ratio - Math.round(ratio)) < 1e-10
  return isInteger ? ratio : Number(ratio.toFixed(decimal))
}
